package louis.echarts.service;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import louis.echarts.util.Base64Util;
import louis.echarts.util.EChartsUtil;
import louis.echarts.util.FreemarkerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

/**
 * @Description ECharts 图表服务层
 * @Author Louis
 * @Date 2022/07/10 17:14
 */
@Slf4j
@Service
public class EChartsService {

    // PhontomJS 服务网址
    @Value("${phantomjs.url}")
    private String phantomjsUrl;

    /**
    * @Description 生成图表
    * @Return java.io.File
    * @Author Louis
    * @Date 2022/07/10 17:30:19
    */
    public File generateEcharts(String templateName){
        // 数据参数，可以自己通过API查询json数据
        String title = "汽车业务发展情况";
        // 模板参数
        HashMap<String, Object> data = new HashMap<>();
        data.put("title", title);

        List<Map<String, Object>> list = new ArrayList<>();

        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("product","销量(亿)");
        map1.put("2015","50");
        map1.put("2016","70");
        map1.put("2017","142");
        list.add(map1);

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("product","成本(亿)");
        map2.put("2015","40");
        map2.put("2016","50");
        map2.put("2017","75");
        list.add(map2);

        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("product","盈利(亿)");
        map3.put("2015","10");
        map3.put("2016","20");
        map3.put("2017","67");
        list.add(map3);

        //[{ product: '销量', '2015': 43.3, '2016': 85.8, '2017': 93.7 },{ product: '成本', '2015': 83.1, '2016': 73.4, '2017': 55.1 }]
        data.put("source", JSON.toJSONString(list));
        // 调用模板加载数据
        String option = FreemarkerUtil.generate(templateName, data);
        // 生成图片的base64编码
        String base64 = EChartsUtil.generateEChartsBase64(phantomjsUrl, option);
        // 将base64转为文件
        return Base64Util.base64ToFile(base64);
    }

}
